package com.codeplateform.controller;

import com.alibaba.druid.util.StringUtils;
import com.codeplateform.common.JwtUtils;
import com.codeplateform.common.ResultModel;
import com.codeplateform.common.db.LoginDto;
import com.codeplateform.dao.entity.LoginLog;
import com.codeplateform.dao.entity.Register;
import com.codeplateform.service.LoginLogService;
import com.codeplateform.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

@Slf4j
@RestController

public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private LoginLogService logInfo;


    @PostMapping("/")
    public String test() {
        return "Hello, World";
    }


    @PostMapping("/login")
    public ResultModel login(@RequestBody LoginDto loginDto, HttpServletRequest request) {
        log.info("进入登录接口,登录者的信息为：{}", loginDto);
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    try {
                        ipAddress = InetAddress.getLocalHost().getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            // 通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null) {
                if (ipAddress.contains(",")) {
                    ipAddress = ipAddress.split(",")[0];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("登陆人ip为:{}", ipAddress);
        if (loginDto == null) {
            return ResultModel.error(200, "请求参数为空");
        }
        loginDto.setIp(ipAddress);
        Register register = new Register();
        if (!StringUtils.isEmpty(loginDto.getUsername())) {
            register.setUsername(loginDto.getUsername());
        }
        if (!StringUtils.isEmpty(loginDto.getPassword())) {
            register.setPassword(loginDto.getPassword());
            log.info("查询登录人信息为:{}", register);
        }
        Register result = loginService.select(register);
        if (null != result) {
            String token = JwtUtils.createToken(result.getUserId());
            loginDto.setToken(token);
            loginDto.setId(result.getUserId());
            //记录登录信息
            LoginLog loginLog = new LoginLog();
            loginLog.setId(result.getUserId());
            loginLog.setLoginIp(loginDto.getIp());
            loginLog.setLoginTime(new Date());
            loginLog.setName(loginDto.getUsername());
            loginLog.setRemark(0);
            int i = logInfo.log_info(loginLog);
            if (i == 1) {
                return ResultModel.success(loginDto);
            }
            return ResultModel.error(500, "存储登录记录失败");
        }


        return ResultModel.error(400, "登录失败");
    }

 /*   @RequestMapping(value = "/getClaim", method = RequestMethod.GET)
    public ResultModel getClaim(@RequestParam String token) {
        if (!StringUtils.isEmpty(token)) {
            if (JwtUtils.verify(token)) {
                String id = JwtUtils.getClaimByName(token, "id");
                return ResultModel.success("当前登陆人id为:",id);
            } else {
                return ResultModel.error(500, "token失效");
            }
        } else {
            return ResultModel.error(200, "请求参数为空");
        }
    }*/

    @RequestMapping(value = "/loginOut",method = RequestMethod.POST)
    public ResultModel loginOut(@RequestParam String userId){


        return ResultModel.success("注销成功");

    }
}

